﻿using RoadQualityEvalAPI.Models;
using RoadQualityEvaluatorData.Domain.Entities;
using RoadQualityEvaluatorData.DomainServices.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace RoadQualityEvalAPI.Controllers
{
    public class LocationController : ApiController
    {
        LocationRepository _locationRepo;

        public List<LocationModel> GetAllLocations()
        {
            var locations = new List<LocationModel>();

            _locationRepo = new LocationRepository();


            if (_locationRepo.GetAll().Count > 0)
            {
                foreach (var loc in _locationRepo.GetAll())
                {
                    locations.Add(new LocationModel()
                    {
                        Latitude = loc.Latitude,
                        Longitude = loc.Longitude
                    });
                }
            }

            return locations;
        }

        public LocationModel GetLocation(int id)
        {
            _locationRepo = new LocationRepository();

            var l = _locationRepo.GetById(id);

            if (l == null)
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));


            return new LocationModel() { Latitude = l.Latitude, Longitude = l.Longitude };
        }

        public LocationModel GetLocation(double latitude, double longitude)
        {
            _locationRepo = new LocationRepository();

            var l = _locationRepo.GetLocationByLatitudeLongitude(latitude, longitude);

            if (l == null)
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));

            return new LocationModel() { Latitude = l.Latitude, Longitude = l.Longitude };
        }

        [HttpPost]
        public void AddLocation(LocationModel location)
        {
            _locationRepo = new LocationRepository();

            if (ModelState.IsValid)
            {
                _locationRepo.Add(new Location()
                {
                    Longitude = location.Longitude,
                    Latitude = location.Latitude
                });
            }
        }


        [HttpPost]
        public void AddLocationList(List<LocationModel> locations)
        {
            _locationRepo = new LocationRepository();

            if (locations != null && locations.Count > 0)
            {
                foreach (var loc in locations)
                {
                    Location x = new Location()
                    {
                        Latitude = loc.Latitude,
                        Longitude = loc.Longitude
                    };

                    _locationRepo.Add(x);
                }
            }
        }



    }
}
